<template>
    <UxDialog :visible="!!visible" @show="onShow()" @close="onClose()" key="products">
        <div class="layout-product">

            <!-- 加载中 -->
            <UxLoading2 class="product-warp-loading" :loading="loading" />

            <p ref="backTop" @click="backTop">top</p>
            <!-- v-if 每次进来重置数据 -->
            <ProductListHead class="layout-product-head" :query.sync="query" @queryChange="queryChange($event)" />
            <div class="layout-product-content">
                <div class="layout-product-aside">
                    <!-- v-if 每次进来重置数据 -->
                    <ProductLeftMenu :query="query" @queryChange="queryChange($event)" />
                </div>

                <div class="layout-product-warp" :type="type" @click="onSelectEvent($event)">
                    <!-- 为空 -->
                    <div class="product-warp-empty" v-show="!loading && productList.length == 0">
                        <img src="https://img.podpartner.com/static/images-20230202/listEmpty.png" alt="" />
                        <p>No content found</p>
                        <button @click="reset()">Browse products</button>
                    </div>
                    <!-- 有数据 -->
                    <ProductListSort v-show="!loading && productList.length > 0" class="product-warp-list" :query="query" :list="productList" :total="productTotal" @queryChange="queryChange($event)" />
                </div>
            </div>
        </div>
    </UxDialog>
</template>
<script>
export default {
    name: "SelectDialog",
    data () {
        return {
            type: '',
            visible: null,
            leftFixed: false,
            loading: false,
            inited: false,
            query: {
                classify: 0, // 分类[]
                type: "", // 类型[|new|collect]
                surface: [], // 打印面
                brands: [], // 品牌
                sizes: [],
                sort: 1, // 排序
                page: 1, // 当前分页
                limit: 9, // 分页每页条数
            },
            productList: [],
            productTotal: 0,
        };
    },
    // watch: {
    //     value (v) {
    //         if (v) {
    //             this.$nextTick(() => {
    //                 this.backTop();
    //             });
    //         }
    //     },
    // },
    methods: {
        backTop () {
            let dom = this.$refs.backTop;
            dom && dom.scrollIntoView(true);
        },
        // 改变数据
        queryChange (event) {
            let option = event || {};
            let keys = Object.keys(this.query);
            let route = JSON.parse(JSON.stringify(this.query));

            Object.keys(option).map((key) => {
                if (keys.indexOf(key) < 0) {
                    // 没有定义的字段不处理
                } else {
                    this.query[key] = option[key];
                }
            });

            if (JSON.stringify(route) == JSON.stringify(this.query)) {
                // 数据相同，不处理
            } else {
                let query = this.query;
                let form = {};

                query.type && (form.type = query.type);
                query.page > 1 && (form.page = query.page);
                query.sort > 1 && (form.sort = query.sort);
                query.classify && (form.classify = query.classify);
                query.brands.length > 0 &&
                    (form.brands = query.brands.join(","));
                query.sizes.length > 0 && (form.sizes = query.sizes.join(","));

                query.surface.length > 0 &&
                    (form.surface = query.surface.join(","));

                this.loading = true;
                this.getProductList(query).then((response) => {
                    this.productList = response.list;
                    this.productTotal = response.total;
                    this.loading = false;
                });
            }
        },

        // 重置
        reset () {
            let query = JSON.parse(JSON.stringify(this.query));
            query.brands = [];
            query.surface = [];
            query.sizes = [];
            query.page = 1;
            query.sort = 1;
            query.page = 1;
            query.type = null;
            this.queryChange(query);
        },

        async getProductList (query) {
            let list = [];
            let total = 0;

            if (query.type == "collect") {
                // 我的收藏，一次取全部，未做分页处理
                if (process.client) {
                    let response = await this.$http("Product.getCollectList");

                    let page = Math.max(query.page, 1);
                    let start = (page - 1) * query.limit;
                    let stop = page * query.limit;
                    let data = response.data || [];

                    total = data.length || 0;
                    list = data.slice(start, stop);
                } else {
                    // 不在客户端不管他
                }
            } else if (query.type == "new") {
                // 最新的
                // 取所有数据，取31天以内的时间
                let request = { page_size: 999, page_num: 1 };
                let response = await this.$http("Product.getList/", request);

                let time = new Date().getTime() - 86400000 * 31;
                let page = Math.max(query.page, 1);
                let start = (page - 1) * query.limit;
                let stop = page * query.limit;
                let data = (response.data || []).filter(
                    (i) =>
                        parseInt((i.created_at + "0000000").substr(0, 13)) >
                        time
                );

                // 排序
                data.sort((a, b) => b.created_at - a.created_at);
                list = data.slice(start, stop);
                total = data.length || 0;
            } else {
                // 正常
                let request = {};

                request.page_num = query.page || 1;
                request.page_size = query.limit;

                query.sort && (request.sort_status = query.sort);
                query.classify && (request.classify = query.classify);
                query.brands.length > 0 &&
                    (request.brand_list = query.brands.join("|"));
                query.sizes.length > 0 &&
                    (request.size_list = query.sizes.join("|"));
                if (query.surface.length > 0) {
                    let surface = query.surface.map((item) => item.split("-").map((i) => i.replace(/\b\w/, (s) => s.toUpperCase())).join(" "));
                    request.printable_surface = surface.join("|");
                }

                let response = await this.$http("Product.getList/", request);
                list = response.data || [];
                total = response.total || 0;
            }

            return {
                list: list,
                total: total,
            };
        },

        async onShow () {
            // 每次进来重置数据(f)
            // this.resetData();
            if (this.productList.length == 0) {
                this.loading = true;
                let response = await this.getProductList(this.query);
                this.productList = response.list;
                this.productTotal = response.total;
                this.inited = true;
                this.loading = false;
            }
        },

        // 打开
        open (callback) {
            this.visible = (spu) => callback && callback(spu)
            this.type = callback ? 'select' : 'normal';
            this.$nextTick(() => this.backTop());
        },


        // 拦截事件
        onSelectEvent (event) {
            if (this.visible && this.type == 'select') {
                const target = event.target || event.srcElement;
                const link = target.closest('li')
                const spu = link ? link.getAttribute('spu') : '';

                if (spu) {
                    event.preventDefault()
                    event.stopPropagation()
                    this.visible(spu)
                    this.visible = null;
                }
            }
        },

        onClose () {
            if (this.visible) {
                this.visible();
                this.visible = null;
            }
        },
        resetData () {
            Object.assign(this.$data, this.$options.data());
        },
    },
    created () {
        this.$on("global:productDialogOpen", this.open);
    }
};
</script>
<style lang="scss" scoped>
.layout-product {
    box-sizing: border-box;
    width: calc(100vw - 80px);
    min-width: 960px;
    max-width: 1200px;
    height: calc(100vh - 80px);
    position: relative;
    display: flex;
    flex-direction: column;
    & > p {
        top: 0;
        left: 0;
        position: absolute;
        z-index: -1;
    }
}

.layout-product-head {
    padding: 40px 38px;
    font-size: 32px;
    font-family: Roboto-Medium, Roboto;
    font-weight: 500;
    color: #030303;
    line-height: 36px;
    background: none;
}

.layout-product-content {
    flex: 1;
    display: flex;
    flex-direction: row;
    overflow: hidden;
}

.layout-product-aside {
    width: 200px;
    padding-left: 38px;
    padding-right: 10px;
    overflow: auto;

    .product-aside {
        position: relative;
        top: 0;
    }
}

.layout-product-warp {
    padding-right: 38px;
    padding-left: 10px;
    flex: 1;
    position: relative;
    overflow: auto;

    &::v-deep .product-list {
        margin-left: -10px;
        margin-right: -10px;
        li {
            margin-left: 10px;
            margin-right: 10px;
            width: calc(33.33% - 20px);
        }
    }

    &[type='select']::v-deep .product-list {
        li {
            cursor: pointer;
        }
        a {
            pointer-events: none;
        }
    }
}

.product-warp-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    left: 220px !important;
    top: 0;
    right: 0;
    bottom: 0;
    border-radius: 10px;
    background: none !important;
}
.product-warp-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #aaaaaa;
    height: 100%;

    img {
        width: 264px;
        height: 180px;
        margin: 0 0 96px 0;
    }

    button {
        margin: 20px 0 0 0;
        width: 238px;
        height: 52px;
    }
}
</style>
